
package com.syde322;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.syde322.LocationApp.R;
import com.syde322.FactSearch;
import com.syde322.WikiFactSearch;
import com.syde322.WikiFacts;
import com.syde322.myItemizedOverlay;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class LocationAppActivity extends MapActivity {
	
	// Members
	private static LocationProcessor loc_proc;
	private FactSearch<WikiFacts> wikiFactSearch = new WikiFactSearch();
	private ProgressDialog progressDialog;
	private MapView mapView;
	private String fact;
	
	public void init() {
		loc_proc = new LocationProcessor(this);
		loc_proc.init();
	}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.init();
        
        // Button Callback
        /*
        Button fact_button = (Button)findViewById(R.id.button1);
        fact_button.setOnClickListener(new OnClickListener() {
        	public void onClick(View v){
                LocationAppActivity.loc_proc.getLocationForProcessing();
                String query = "Toronto"; // Jason, put the location string in here. 
                You can do Toronto%20Ontario if you want to use multiple words
				performSearch(query);
        	}
        });
        */
        
        this.loc_proc.getLocationForProcessing();
        Location x = LocationProcessor.getLocation();
        
        instantiateMap(x);	
    }
    
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
	/** Register for the updates when Activity is in foreground */
	
   /* @Override
	protected void onResume() {
		super.onResume();
		//this.loc_proc.getLocationManager().requestLocationUpdates(this.loc_proc.getBestProvider(), 20000, 1, (LocationListener) this);
	}
	
	*//** Stop the updates when Activity is paused to save CPU *//*
	@Override
	protected void onPause() {
		super.onPause();
		//this.loc_proc.getLocationManager().removeUpdates((LocationListener) this);
	}
	*/
	
    //sets up the MapView - takes in a location object from getLocationForProcessing, uses the coordinates to find location, passes location to wiki search 
	public void instantiateMap(Location currLoc) {
    	mapView = (MapView) findViewById(R.id.map_view);   //getting map        
    	mapView.setBuiltInZoomControls(true);
    	
    	List<Overlay> mapOverlays = mapView.getOverlays();//drawing something on screen
        Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
        myItemizedOverlay itemizedoverlay = new myItemizedOverlay(drawable, this);
       

        double lat = (currLoc.getLatitude()); //getting latitude and longitude from that object in decimal
        double lng = (currLoc.getLongitude());
        int latE = (int) (currLoc.getLatitude()*1000000);
        int lngE = (int) (currLoc.getLongitude()*1000000);//in integer format
        
        //manual input of coordinates
        //GeoPoint point = new GeoPoint(43464258,-80520410);
        Log.d("LocationProcessor", "Lat: "+lat);//saving latitude/long
        Log.d("LocationProcessor", "Long: "+lng);//log-google class and d a fun of that class
        
        Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());//initialization
        
        List<Address> myList = null; 
        
	//gets location from latitude longitude
////the important thing is  that the result of the getlocation is stored in myList - thats your list of all the
 //possible cities
        try {
			myList = myLocation.getFromLocation(lat, lng, 1);
		} catch (IOException e) {
			e.printStackTrace();
		}


////storing locality of city and admin area
        if (myList != null) {
        	Log.d("LocationProcessor", "Reverse Geocode Results: "+myList.get(0).getLocality());
        	Log.d("LocationProcessor", "Reverse Geocode Results: "+myList.get(0).getAdminArea());
        	//Log.d("LocationProcessor", "Reverse Geocode Results: "+myList.get(0).getCountryName());
        	
////makes one string from those 2 separated by comma
        	String query = myList.get(0).getLocality()+", "+myList.get(0).getAdminArea(); /// Jason, put the location string in here. You can do Toronto%20Ontario if you want to use multiple words
        	private void performSearch(String query) {//call perform search with that string
	        progressDialog = ProgressDialog.show(LocationAppActivity.this,
	                "Please wait...", "Retrieving data...", true, true);
	        
	        DoWikiSearch task = new DoWikiSearch();//creates object of class called task
	            task.execute(query);//starts thread 2
	            progressDialog.setOnCancelListener(new CancelTaskOnCancelListener(task));//listener listens to main thread
	}
        	//need the query returns here and pass it to the overlay items below 
	/** perform Asynchronous HTTP Request */
	private class DoWikiSearch extends AsyncTask<String, Void, List<WikiFacts>> {
    	
    	@Override
    	public List<WikiFacts> doInBackground(String... params) {
    		String query = params[0];
        	//Log.d(getClass().getSimpleName(), "START ASYNC, QUERY : " + query);
    		return wikiFactSearch.find(query);//returns a list of facts
    	}
    	
    	@Override
    	public void onPostExecute(final List<WikiFacts> result) {//runs on main thread
    		runOnUiThread(new Runnable() {//remove this line if app doesn't run
    	    	public void run() {//remove this iff
    	    		if (progressDialog!=null) {
    	    			progressDialog.dismiss();
    	    			progressDialog = null;
    	    		}
    	    		if (result!=null) {
    						// Data is returned here
    	    			fact = new String(WikiFacts.title + " - " + WikiFacts.description);
    						Log.d("Results", WikiFacts.title + " - " + WikiFacts.description);
    				}
    	    	}//remove this iff
    	    });//remove this iff
    	}
    }
    
        }
        else 
        	Log.d("LocationProcessor", "Reverse Geocode Results: List is null :(");
        
        // Delete this - GeoPoint point = new GeoPoint(latE, lngE);
        
        // Delete this -OverlayItem overlayitem = new OverlayItem(point, myList.get(0).getLocality()+", "+myList.get(0).getAdminArea(), "It is the smallest of the three cities in the Regional Municipality of Waterloo, and is adjacent to the city of Kitchener.");
        GeoPoint point = new GeoPoint(latE, lngE);
        //Adding section
        if (fact != "")
            OverlayItem overlayitem = new OverlayItem(point, myList.get(0).getLocality()+", "+myList.get(0).getAdminArea(), fact);
    else
            OverlayItem overlayitem = new OverlayItem(point, myList.get(0).getLocality()+", "+myList.get(0).getAdminArea(), "Sorry, could not retreive facts at this time");
        
        itemizedoverlay.addOverlay(overlayitem);
        mapOverlays.add(itemizedoverlay);
        
        mapView.getController().setZoom(15);
        mapView.getController().setCenter(point);
    }
	
/** ============== Ting's Wiki Search ================== **/
	
	/** perform Asynchronous HTTP Request */
    
    /** start WikiSearch */

	/** Cancel WikiSearch if user clicks Cancel in Dialog **/
	private class CancelTaskOnCancelListener implements OnCancelListener {
		private AsyncTask<?, ?, ?> task;
		public CancelTaskOnCancelListener(AsyncTask<?, ?, ?> task) {
			this.task = task;
		}
		public void onCancel(DialogInterface dialog) {
			if (task!=null) {
	    		task.cancel(true);
	    	}
		}
	}
}
